/* eslint-disable indent */
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片   -->
    <el-card>
      <el-alert
        title="注意：只允许修改第三级分类的相关参数"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品级联框 -->
      <el-row style="margin-top:15px">
        <el-col>
          <span>商品分类：</span>
          <el-cascader
            clearable
            v-model="selectKeys"
            :options="cateList"
            :props="cascaderProps"
            :show-all-levels="false"
            @change="handelChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 标签页 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <!-- 动态参数 -->
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            type="primary"
            :disabled="isBtDisabled"
            @click="showAddParamDialog"
          >动态参数</el-button>
          <el-table
            :data="manyCateParam"
            border
            stripe
          >
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag
                  style="margin:0 15px"
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteTag(scope.row,i)"
                >{{item}}
                </el-tag>
                <!-- 添加新tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="addTag(scope.row)"
                  @blur="addTag(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
            >
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- eslint-disable-next-line vue/no-unused-vars -->
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="error"
                  icon="el-icon-edit"
                  @click="deleteParam(scope.row.attr_id)"
                > 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            type="primary"
            :disabled="isBtDisabled"
            @click="showAddParamDialog"
          >静态属性</el-button>
          <el-table
            :data="onlyCateParam"
            border
            stripe
          >
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag
                  style="margin:0 15px"
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteTag(scope.row,i)"
                >{{item}}
                </el-tag>
                <!-- 添加新tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="addTag(scope.row)"
                  @blur="addTag(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
            >
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- eslint-disable-next-line vue/no-unused-vars -->
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="error"
                  icon="el-icon-edit"
                  @click="deleteParam(scope.row.attr_id)"
                > 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->

    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamDialogVisible"
      width="60%"
      @close="addParamDialogClose"
    >
      <el-form
        :model="addParamForm"
        :rules="addParamRules"
        ref="addParamRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="titleText"
          prop="attr_name"
        >
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addParamDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addParam"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamDialogVisible"
      width="60%"
      @close="editParamDialogClose"
    >
      <el-form
        :model="editParamForm"
        :rules="editParamRules"
        ref="editParamRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="titleText"
          prop="attr_name"
        >
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveEditParam"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      selectKeys: [],
      cateList: [],
      // 配置选项
      cascaderProps: {
        expandTrigger: 'hover',
        checkStrictly: false,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 标签页标题
      activeName: 'many',
      manyCateParam: [],
      onlyCateParam: [],
      addParamDialogVisible: false,
      editParamDialogVisible: false,
      // 修改参数的id
      cat_id: '',
      addParamForm: {
        attr_name: ''
      },
      editParamForm: {},
      addParamRules: {
        attr_name: [
          { required: true, message: '请输入分类名', trigger: 'blur' }
        ]
      },
      editParamRules: {
        attr_name: [
          { required: true, message: '请输入分类名', trigger: 'blur' }
        ]
      },

    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取产品列表失败！')
      }
      this.cateList = res.data
      //   console.log(res.data)
    },
    // 级联框改变选择
    async handelChange () {
      this.cat_id = this.selectKeys[this.selectKeys.length - 1]
      this.getCateParam()
    },
    // tab切换
    async handleClick () {
      //   console.log(this.selectKeys.length)
      if (!this.selectKeys.length) {
        return this.$message.error('请选择相关产品')
      }
      this.getCateParam()
    },
    // 封装尝试
    /* eslint-disable*/
    async httpMethod (method, path, params) {
      switch (method) {
        case 'get':
          {
            // console.log('2', params)
            const { data: res } = await this.$http.get(path, params)
            return res
          }
        case 'post':
          {
            const { data: res } = await this.$http.post(path, params)
            return res
          }
        case 'put':
          {
            const { data: res } = await this.$http.put(path, params)
            return res
          }
        case 'delete':
          {
            const { data: res } = await this.$http.delete(path, params)
            return res
          }
        default:
          // console.log('请求方法错误，请检查')
          break
      }
      /* eslint-enable */
    },
    // 获取动态/静态参数
    async getCateParam () {
      const { data: res } = await this.$http.get(`categories/${this.selectKeys[this.selectKeys.length - 1]}/attributes`,
        { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取属性失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals !== '' ? item.attr_vals.split(',') : []
        // 添加tag控制
        item.inputVisible = false
        item.inputValue = ''
      })

      // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyCateParam = res.data
      } else {
        this.onlyCateParam = res.data
      }
      // console.log('many', this.manyCateParam)
      // console.log('only', this.onlyCateParam)
      //   console.log(this.activeName)
      // console.log('http', await this.httpMethod('get', `categories/${this.selectKeys[this.selectKeys.length - 1]}/attributes`,
      // { params: { sel: this.activeName } }))
    },
    showAddParamDialog () {
      this.addParamDialogVisible = true
    },
    addParamDialogClose () {
      this.$refs.addParamRef.resetFields()
    },
    // 添加分类提交
    addParam () {
      this.addParamDialogVisible = false
      this.$refs.addParamRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请完成表单')
        }
        const { data: res } = await this.$http.post(`categories/${this.cat_id}/attributes`,
          {
            attr_name: this.addParamForm.attr_name,
            attr_sel: this.activeName
          })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.getCateParam()
        // console.log('res', res)
      })
      // console.log(this.$refs.addParamRef)
    },
    // 添加标签tag提交
    addTag (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果有数据，进行提交
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveTag(row)
      // console.log(this.inputValue)
    },
    // 封装添加tag函数
    async saveTag (row) {
      const { data: res } = await this.$http.put(`categories/${this.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        })
      // console.log(res)
      if (res.meta.status !== 200) {
        row.attr_vals.pop()
        return this.$message.error('添加新新属性值失败')
      }
    },
    showInput (row) {
      row.inputVisible = true
      // $nextTick 方法的作用，就是页面元素被重新渲染后执行函数中的
      // 回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag标签
    deleteTag (row, i) {
      row.attr_vals.splice(i, 1)
      this.saveTag(row)
    },
    editParamDialogClose () {
      this.$refs.editParamRef.resetFields()
    },
    async showEditParamDialog (attrId) {
      // 不使用scope.row的数据。因为后台数据可能已经更新了
      this.editParamDialogVisible = true
      // const { data: res } = await this.httpMethod('get', `categories/${param.cat_id}/attributes/${param.attr_id}`,
      //  { params: { attr_sel: this.activeName } })
      //   console.log('res', res)
      const { data: res } = await this.$http.get(`categories/${this.cat_id}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      this.editParamForm = res.data
      //   this.editParamForm.attr_name = param.attr_name
      //   console.log(param)
    },
    // 提交修改后的表格
    saveEditParam () {
      this.$refs.editParamRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请输入添加的分类名')
        }
        const { data: res } = await this.$http.put(`categories/${this.cat_id}/attributes/${this.editParamForm.attr_id}`,
          { attr_name: this.editParamForm.attr_name, attr_sel: this.activeName })
        this.getCateParam()
        // console.log(this.activeName, res)
      })
      this.editParamDialogVisible = false
    },
    // 删除参数
    async deleteParam (attrId) {
      const res = await this.$confirm('此操作将永久删除该商品参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(res)
      if (res !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res1 } = await this.$http.delete(`categories/${this.cat_id}/attributes/${attrId}`)
      if (res1.meta.status !== 200) {
        // console.log(res1)
        return this.$message.error('删除参数失败！')
      }
      this.$message.success('删除参数成功！')
      this.getCateParam()
    }
  },
  computed: {
    isBtDisabled () {
      if (!this.selectKeys.length) {
        return true
      } else {
        return false
      }
    },
    // 动态计算添加属性对话框的动态/静态
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.input-new-tag {
  width: 130px;
}
</style>
